package com.web.homework01;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;

@WebServlet(urlPatterns = "/load")
public class Load extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html;charset=UTF-8");
        String userName = req.getParameter("userName");
        String password = req.getParameter("password");

        if (userName == null || userName.trim().equals("")) {
            resp.getWriter().write("用户名不能为空");
            System.out.println("空用户名");
            return;
        }
        if (password == null || password.trim().equals("")) {
            resp.getWriter().write("密码不能为空");
            System.out.println("空密码");
            return;
        }

        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = "jdbc:mysql://127.0.0.1:3306/demo";
            Connection conn = DriverManager.getConnection(url, "root", "root");
            PreparedStatement stmt = conn.prepareStatement("select password,username from users where username = ?");
            stmt.setString(1, userName);
            ResultSet rs = stmt.executeQuery();
            if (rs.next()) {
                String pass = rs.getString("password");
                String user = rs.getString("username");
                if (userName.equals(user) && password.equals(pass)) {
                    resp.getWriter().write("登录成功");
                    if ("free".equals(req.getParameter("free"))) {
                        //存储在cookie中
                        Cookie userc = new Cookie("userName", userName);
                        Cookie passc = new Cookie("password", password);
                        userc.setMaxAge(60 * 60 * 24 * 7);
                        passc.setMaxAge(60 * 60 * 24 * 7);
                        resp.addCookie(userc);
                        resp.addCookie(passc);
                    }
                    return;
                }
            }
        } catch (ClassNotFoundException | SQLException e) {
            throw new RuntimeException(e);
        }
        resp.getWriter().write("账号或密码错误");

    }
}